package com.zhixuan.autoui.sample;

import android.content.Context;
import android.content.Intent;
import android.media.AudioFocusRequest;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.tinker.core.misc.gain.GainCategory;
import com.tinker.core.misc.volume.VolumeCategory;
import com.tinker.coresdk.manager.ZXFocusStackManager;
import com.tinker.coresdk.manager.ZXSoundEffectManager;
import com.tinker.coresdk.manager.ZXSpeechRecognitionManager;
import com.tinker.coresdk.manager.ZXSystemManager;
import com.tinker.coresdk.model.SpeechCommand;
import com.tinker.coresdk.release.iface.SoundEffectTool;
import com.tinker.coresdk.release.iface.SpeechRecognitionTool;
import com.tinker.coresdk.release.iface.SystemObserver;
import com.tinker.pojo.EqualizerConfig;
import com.zhixuan.autoui.R;

import java.util.Arrays;

import cd.zhixuan.utils.recycler.RecyclerGridSelectTextView;
import cd.zhixuan.utils.recycler.adapter.BaseRecyclerAdapter;
import cd.zhixuan.utils.recycler.adapter.RecyclerListAdapter;
import cd.zhixuan.utils.recycler.adapter.listener.OnBindHolder;
import cd.zhixuan.utils.recycler.adapter.listener.OnItemClickListener;
import cd.zhixuan.utils.recycler.layout_manager.Check;
import cd.zhixuan.utils.recycler.layout_manager.OpenStaggerGridLayoutManager;

/**
 * author: HuZC
 * Date: 2021/11/22
 * Description:
 */
public class SpeechRecognitionActivity extends BaseTestActivity {

    private TextView tvMsg;

    @Override
    protected int onContentLayout() {
        return R.layout.sample_activity_speech_recognition;
    }

    @Override
    protected void onCreated(Bundle savedInstanceState) {

        tvMsg = findViewById(R.id.tv_msg);

        initView();
        initAutoManagerListener();

    }

    private void initAutoManagerListener() {
        ZXSpeechRecognitionManager.getInstance().setTool(new SpeechRecognitionTool() {
            @Override
            public void onSpeechRecognitionRecoderStateChange(int i) {
                addMessage("onSpeechRecognitionRecoderStateChange: " + i);
            }

            @Override
            public void onSpeechRecognitionUITypeChange(int i) {
                addMessage("onSpeechRecognitionUITypeChange: " + i);
            }

            @Override
            public void onSpeechRecognitionAsrRawText(String s) {
                addMessage("onSpeechRecognitionAsrRawText: " + s);
            }

            @Override
            public void onSpeechRecognitionAsrControlCommand(String s) {
                addMessage("onSpeechRecognitionAsrControlCommand: " + s);
            }

            @Override
            public void onSpeechRecognitionTtsState(int i) {
                addMessage("onSpeechRecognitionTtsState: " + i);
            }

            @Override
            public void onRequestTtsPlayResult(String s, int i, String s1, int i1) {
                addMessage("onRequestTtsPlayResult: " + s + " , " + i + " , " + s1 + " , " + i1);
            }

            @Override
            public void onSpeechRecognitionDialogShow() {
                addMessage("弹出语音识别UI");
            }

            @Override
            public void onSpeechRecognitionDialogHide() {
                addMessage("关闭语音识别UI");
            }

            @Override
            public void onSpeechRecognitionDialogText(String s) {
                addMessage("关闭语音识别TEXT:" + s);
            }
        });
        ZXSoundEffectManager.getInstance().setTool(new SoundEffectTool() {
            @Override
            public void onSystemVolumeChangeByUser(String s, String s1, int i) {
                addMessage("onSystemVolumeChangeByUser:" + s + "," + s1 + "," + i);
            }

            @Override
            public void onVolumeCategoryConfigFinish(VolumeCategory volumeCategory) {
                addMessage("onVolumeCategoryConfigFinish:" + volumeCategory);

            }

            @Override
            public void onGainCategoryConfigFinish(GainCategory gainCategory) {
                addMessage("onGainCategoryConfigFinish:" + gainCategory);

            }

            @Override
            public void onEqualizerConfigFinish(EqualizerConfig equalizerConfig) {
                addMessage("onEqualizerConfigFinish:" + equalizerConfig);

            }

            @Override
            public void onSystemVolumeChange(String s, String s1, int i) {
                addMessage("onSystemVolumeChange:" + s + "," + s1 + "," + i);

            }

            @Override
            public void onVolumeGainChange(String s, String s1, int i) {
                addMessage("onVolumeGainChange:" + s + "," + s1 + "," + i);

            }

            @Override
            public void onSystemMuteChange(boolean b) {
                addMessage("onSystemMuteChange:" + b);

            }

            @Override
            public void onVolumeCategoryMuteChange(String s, boolean b) {
                addMessage("onVolumeCategoryMuteChange:" + s + "," + b);

            }

            @Override
            public void onSetSoundField(byte b, byte b1) {
                addMessage("onSetSoundField:" + b + "," + b1);

            }

            @Override
            public void onSetSoundEffect(byte b, byte b1, byte b2, byte b3, byte b4, byte b5) {
                addMessage("onSetSoundEffect:" + b + "," + b1 + "," + b2 + "," + b3 + "," + b4 + "," + b5);

            }

            @Override
            public void onSetSoundEffectEQ(byte b, byte[] bytes) {
                addMessage("onSetSoundEffectEQ:" + b + "," + Arrays.toString(bytes));

            }

            @Override
            public void onPresetsForEqualizer(int i) {
                addMessage("onPresetsForEqualizer:" + i);

            }

            @Override
            public void onSetSubwooferGain(int i) {
                addMessage("onSetSubwooferGain:" + i);

            }

            @Override
            public void onSetSubwooferGainPower(boolean b) {
                addMessage("onSetSubwooferGainPower:" + b);

            }

            @Override
            public void onSetSubwooferLPF(int i) {
                addMessage("onSetSubwooferLPF:" + i);

            }

            @Override
            public void onSetSubwooferPhase(int i) {
                addMessage("onSetSubwooferPhase:" + i);

            }

            @Override
            public void onSetNaviMixerType(int i) {
                addMessage("onSetNaviMixerType:" + i);

            }

            @Override
            public void onSetNaviVoiceChannel(int i) {
                addMessage("onSetNaviVoiceChannel:" + i);

            }

            @Override
            public void onSetBeep(boolean b) {
                addMessage("onSetBeep:" + b);

            }

            @Override
            public void onSetLoudnessSwitcher(boolean b) {
                addMessage("onSetLoudnessSwitcher:" + b);

            }

            @Override
            public void onSetLoudnessLevel(int i) {
                addMessage("onSetLoudnessLevel:" + i);

            }

            @Override
            public void onSetBTVoiceChannelMode(int i) {
                addMessage("onSetBTVoiceChannelMode:" + i);

            }

            @Override
            public void onSetNaviChannel(int i) {
                addMessage("onSetNaviChannel:" + i);

            }

            @Override
            public void onRequestSetVolumeByCategory(String s, int i) {
                addMessage("onRequestSetVolumeByCategory:" + s + "," + i);

            }

            @Override
            public void onRequestSetVolumeUIByCategory(String s, int i, boolean b) {
                addMessage("onRequestSetVolumeUIByCategory:" + s + "," + i + "," + b);

            }

        });
        //
        ZXSystemManager.getInstance().setTool(new SystemObserver() {
            @Override
            public void onSetBacklight(int level) {
                addMessage("收到设置背光亮度通知： level=" + level);
            }
        });
    }

    private void initView() {
        initMusic();
        initPhone();
    }

    private void initMusic() {
        RecyclerGridSelectTextView<String> rgstMusic = findViewById(R.id.rgst_music);
//        rgstMusic.getLayoutManager().setSpanCount(2);
        OpenStaggerGridLayoutManager layoutManager = new OpenStaggerGridLayoutManager(2, StaggeredGridLayoutManager.HORIZONTAL);
        layoutManager.setCanScroll(Check.Y);
        rgstMusic.setLayoutManager(layoutManager);
        RecyclerListAdapter<String> adapter = rgstMusic.getAdapter();
        adapter.setDataList(new String[]{"播放音乐", "暂停音乐", "继续播放",
                "关闭音乐", "随便听听", "上一首", "下一首",
                "单曲循环", "顺序播放", "随机播放",
                "播放特定歌曲", "智能播放"
        });
        adapter.setChoiceMode(BaseRecyclerAdapter.ChoiceMode.NONE);
        adapter.setChoiceState(BaseRecyclerAdapter.ChoiceState.NONE);
        adapter.bindHolder(new OnBindHolder<RecyclerView.ViewHolder, String>() {
            @Override
            public void onBind(RecyclerView.ViewHolder viewHolder, String s, int i) {
                TextView text = viewHolder.itemView.findViewById(R.id.text);
                text.setText(s);
            }
        });
        adapter.setOnItemClickListener(new OnItemClickListener<RecyclerView.ViewHolder, String>() {
            @Override
            public boolean onItemClick(RecyclerView.ViewHolder viewHolder, String s, int i) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_LAUNCHER);
//                intent.setClassName("com.zhixuan.android.mediatest", "com.zhixuan.android.mediatest.MediaMainActivity");
                intent.addCategory("ZHIXUAN.CATEGORY.MUSIC_PLAYER");
                SpeechCommand command = new SpeechCommand();
                SpeechCommand.ControlData controlData = new SpeechCommand.ControlData();
                command.data = controlData;

                command.code = SpeechCommand.CODE_MUSIC;
                command.desc = "common music command";
                switch (s) {
                    case "播放音乐":
                        controlData.code = SpeechCommand.CM_PLAY;
                        controlData.cmd = "play";
                        break;
                    case "暂停音乐":
                        controlData.code = SpeechCommand.CM_PAUSE;
                        controlData.cmd = "pause";
                        break;
                    case "继续播放":
                        controlData.code = SpeechCommand.CM_CONTINUE;
                        controlData.cmd = "continue_play";
                        break;
                    case "关闭音乐":
                        controlData.code = SpeechCommand.CM_EXIT;
                        controlData.cmd = "exit";
                        break;
                    case "随便听听":
                        controlData.code = SpeechCommand.CM_RANDOM;
                        controlData.cmd = "random_mode";
                        break;
                    case "上一首":
                        controlData.code = SpeechCommand.CM_TRIGGER;
                        controlData.cmd = "previous";
                        break;
                    case "下一首":
                        controlData.code = SpeechCommand.CM_TRIGGER;
                        controlData.cmd = "next";
                        break;
                    case "单曲循环":
                        controlData.code = SpeechCommand.CM_PLAY_MODE;
                        controlData.cmd = "single";
                        break;
                    case "顺序播放":
                        controlData.code = SpeechCommand.CM_PLAY_MODE;
                        controlData.cmd = "shuffle";
                        break;
                    case "随机播放":
                        controlData.code = SpeechCommand.CM_PLAY_MODE;
                        controlData.cmd = "random";
                        break;
                    case "播放特定歌曲":
                        controlData.code = SpeechCommand.CM_PLAY_TARGET;
                        controlData.data = getTarget();
                        controlData.cmd = targetCmd[targetIndex];
                        break;
                    case "智能播放":
                        controlData.code = SpeechCommand.CM_PLAY_SMART;
                        controlData.cmd = getSmart();
                        break;
                    default:
                        break;
                }
                String json = command.toJson();
                try {
                    ZXSpeechRecognitionManager.getInstance().debugCommand(json);
                } catch (Exception e) {
                    e.printStackTrace();
                }
//                addMessage("发送音乐数据：" + json);
//                intent.putExtra(SpeechCommand.DATA_KEY, json);
//
//                try {
////                    if (DebugUtils.WITHOUT_AUTO_LIB) {
//                    startActivity(intent);
////                    } else {
////                        startActivityAsUser(intent, UserHandle.CURRENT);
////                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }

                return true;
            }

            private int targetIndex = -1;
            private SpeechCommand.Params[] targets;
            private final String[] targetCmd = new String[]{"title", "artist", "album"};

            private SpeechCommand.Params getTarget() {
                if (targets == null) {
                    targets = new SpeechCommand.Params[3];
                    targets[0] = new SpeechCommand.Params();
                    targets[0].title = "I See You";
                    targets[0].artist = "Missio";
                    targets[0].album = "I See You";
                    //
                    targets[1] = new SpeechCommand.Params();
                    targets[1].title = "半兽人";
                    targets[1].artist = "周杰伦";
                    targets[1].album = "八度空间";
                    //
                    targets[2] = new SpeechCommand.Params();
                    targets[2].title = "一起走过的日子";
                    targets[2].artist = "刘德华";
                    targets[2].album = "丽影金曲";
                }
                targetIndex++;
                targetIndex = targetIndex % targets.length;
                return targets[targetIndex];
            }

            private int smartIndex = -1;
            private String[] smart;

            private String getSmart() {
                if (smart == null) {
                    smart = new String[]{
                            "热情歌曲", "90后歌曲", "中文歌曲",
                            "钢琴曲", "摇滚", "胎教音乐"
                    };
                }
                smartIndex++;
                return smart[smartIndex % smart.length];
            }
        });
    }

    private void initPhone() {
        RecyclerGridSelectTextView<String> rgst = findViewById(R.id.rgst_phone);
//        rgstMusic.getLayoutManager().setSpanCount(2);
        OpenStaggerGridLayoutManager layoutManager = new OpenStaggerGridLayoutManager(2, StaggeredGridLayoutManager.HORIZONTAL);
        layoutManager.setCanScroll(Check.Y);
        rgst.setLayoutManager(layoutManager);
        RecyclerListAdapter<String> adapter = rgst.getAdapter();
        adapter.setDataList(new String[]{
                "打电话给联系人", "拨打号码", "接听",
                "挂断", "拒接", "私密模式", "公开模式"
        });
        adapter.setChoiceMode(BaseRecyclerAdapter.ChoiceMode.NONE);
        adapter.setChoiceState(BaseRecyclerAdapter.ChoiceState.NONE);
        adapter.bindHolder(new OnBindHolder<RecyclerView.ViewHolder, String>() {
            @Override
            public void onBind(RecyclerView.ViewHolder viewHolder, String s, int i) {
                TextView text = viewHolder.itemView.findViewById(R.id.text);
                text.setText(s);
            }
        });
        adapter.setOnItemClickListener(new OnItemClickListener<RecyclerView.ViewHolder, String>() {
            @Override
            public boolean onItemClick(RecyclerView.ViewHolder viewHolder, String s, int i) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_DIAL);
                SpeechCommand command = new SpeechCommand();
                SpeechCommand.ControlData controlData = new SpeechCommand.ControlData();
                command.data = controlData;

                command.code = SpeechCommand.CODE_PHONE_CALL;
                command.desc = "common music command";
                switch (s) {
                    case "打电话给联系人":
                        controlData.code = SpeechCommand.CPC_CALL_PEOPLE;
                        controlData.cmd = "makeCall";
                        controlData.data = getPeople();
                        //
                        break;
                    case "拨打号码":
                        controlData.code = SpeechCommand.CPC_CALL_PEOPLE;
                        controlData.cmd = "makeCall";
                        controlData.data = getPeopleNumb();
                        break;
                    case "接听":
                        controlData.code = SpeechCommand.CPC_PICK_UP;
                        controlData.cmd = "pick_up";
                        break;
                    case "挂断":
                        controlData.code = SpeechCommand.CPC_HANG_UP;
                        controlData.cmd = "hang_up";
                        break;
                    case "拒接":
                        controlData.code = SpeechCommand.CPC_REJECT;
                        controlData.cmd = "reject_phone";
                        break;
                    case "私密模式":
                        controlData.code = SpeechCommand.CPC_PRIVATE_MODE;
                        controlData.cmd = "private_mode";
                        break;
                    case "公开模式":
                        controlData.code = SpeechCommand.CPC_PUBLIC_MODE;
                        controlData.cmd = "public_mode";
                        break;
                    default:
                        break;
                }
                String json = command.toJson();
                addMessage("发送电话数据：" + json);
                intent.putExtra(SpeechCommand.DATA_KEY, json);
                try {
                    intent.setData(Uri.parse("tel:" + controlData.data.number));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                try {
//                    if (DebugUtils.WITHOUT_AUTO_LIB) {
                    startActivity(intent);
//                    } else {
//                        startActivityAsUser(intent, UserHandle.CURRENT);
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return true;
            }

            private int peo2Index = -1;
            private SpeechCommand.Params[] people2;

            private SpeechCommand.Params getPeopleNumb() {
                if (people2 == null) {
                    people2 = new SpeechCommand.Params[3];
                    people2[0] = new SpeechCommand.Params();
                    people2[0].number = "33333333333";
                    //
                    people2[1] = new SpeechCommand.Params();
                    people2[1].number = "44444444444";
                    //
                    people2[2] = new SpeechCommand.Params();
                    people2[2].number = "55555555555";
                }
                peo2Index++;
                peo2Index = peo2Index % people2.length;
                return people2[peo2Index];
            }

            private SpeechCommand.Params[] people;
            private int peoIndex = -1;

            private SpeechCommand.Params getPeople() {
                if (people == null) {
                    people = new SpeechCommand.Params[3];
                    people[0] = new SpeechCommand.Params();
                    people[0].name = "张三";
                    people[0].number = "33333333333";
                    //
                    people[1] = new SpeechCommand.Params();
                    people[1].name = "李四";
                    people[1].number = "44444444444";
                    //
                    people[2] = new SpeechCommand.Params();
                    people[2].name = "王五";
                    people[2].number = "55555555555";
                }
                peoIndex++;
                peoIndex = peoIndex % people.length;
                return people[peoIndex];
            }
        });
    }

    private final int count = 0;

    private final String STRING = "成都智暄科技";

    public void onRequestTtsPlay(View view) {
        addMessage("点击语音播报");
        try {
            ZXSpeechRecognitionManager.getInstance().requestTtsPlay(STRING, 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onSpeechStart(View view) {
        addMessage("点击开始语音识别");
        try {
            ZXSpeechRecognitionManager.getInstance().requestSpeechStart();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onSpeechCancel(View view) {
        addMessage("点击取消语音识别");
        try {
            ZXSpeechRecognitionManager.getInstance().requestSpeechCancel();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void onRequestVoiceFocus(View view) {
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int request = am.requestAudioFocus(getAudioFocusRequest());
        switch (request) {
            case AudioManager.AUDIOFOCUS_REQUEST_GRANTED:
                toast("获取成功");
                Log.d(TAG, "onRequestVoiceFocus : AUDIOFOCUS_REQUEST_GRANTED");
                break;
            case AudioManager.AUDIOFOCUS_REQUEST_FAILED:
                toast("获取失败");
                Log.d(TAG, "onRequestVoiceFocus : AUDIOFOCUS_REQUEST_FAILED");
                break;
            case AudioManager.AUDIOFOCUS_REQUEST_DELAYED:
                Log.d(TAG, "onRequestVoiceFocus : AUDIOFOCUS_REQUEST_DELAYED");
                break;
        }
    }

    public void onReleaseVoiceFocus(View view) {
        if (audioFocusRequest == null) return;
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int request = am.abandonAudioFocusRequest(audioFocusRequest);
        switch (request) {
            case AudioManager.AUDIOFOCUS_REQUEST_GRANTED:
                toast("释放成功");
                Log.d(TAG, "onRequestVoiceFocus : AUDIOFOCUS_REQUEST_GRANTED");
                break;
            case AudioManager.AUDIOFOCUS_REQUEST_FAILED:
                toast("释放失败");
                Log.d(TAG, "onRequestVoiceFocus : AUDIOFOCUS_REQUEST_FAILED");
                break;
            case AudioManager.AUDIOFOCUS_REQUEST_DELAYED:
                toast("释放Delayed");
                Log.d(TAG, "onRequestVoiceFocus : AUDIOFOCUS_REQUEST_DELAYED");
                break;
        }
    }

    private AudioFocusRequest audioFocusRequest;

    private AudioFocusRequest getAudioFocusRequest() {
        if (audioFocusRequest == null) {
            AudioFocusRequest.Builder builder = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
            builder.setAcceptsDelayedFocusGain(true);
            builder.setFocusGain(AudioManager.STREAM_MUSIC);
            builder.setOnAudioFocusChangeListener(new AudioManager.OnAudioFocusChangeListener() {
                @Override
                public void onAudioFocusChange(int focusChange) {
                    if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                        toast("获取到声音焦点");
                    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                        toast("丢失声音焦点");
                    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
                        toast("短暂丢失声音焦点");
                    } else {
                        toast("声音焦点 focusChange:" + focusChange);
                    }
                }
            });
            audioFocusRequest = builder.build();
        }
        return audioFocusRequest;
    }


    public void onRequestTtsStop(View view) {
        addMessage("点击停止语音播报");
        try {
            ZXSpeechRecognitionManager.getInstance().requestTtsStop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onRequestTtsPause(View view) {
        addMessage("点击暂停语音播报");
        try {
            ZXSpeechRecognitionManager.getInstance().requestTtsPause();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onRequestTtsResume(View view) {
        addMessage("点击继续语音播报");
        try {
            ZXSpeechRecognitionManager.getInstance().requestTtsResume();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onRequestTtsRelease(View view) {
        addMessage("点击释放语音播报");
        try {
            ZXSpeechRecognitionManager.getInstance().requestTtsRelease();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onSpeechRelease(View view) {
        addMessage("点击释放语音识别");
        try {
            ZXSpeechRecognitionManager.getInstance().requestSpeechRelease();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onSpeechStop(View view) {
        addMessage("点击停止语音识别");
        try {
            ZXSpeechRecognitionManager.getInstance().requestSpeechStop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void onGetCurVoiceFocus(View view) {
        addMessage("获取当前声音焦点：");
        try {
            String currentTopAudioFocus = ZXFocusStackManager.getInstance().getCurrentTopAudioFocus();
            addMessage(currentTopAudioFocus);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onGetCurMediaFocus(View view) {
        addMessage("获取当前媒体焦点：");
        try {
            String currentTopAudioFocus = ZXFocusStackManager.getInstance().getCurMediaSourcePkg();
            addMessage(currentTopAudioFocus);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
